import { Color, ColorScheme, ColorUsageStats, ActivityData } from '@/types';
import { StorageService } from './storage';
import { ColorUtils } from '@/utils/color';

/**
 * 色彩分析服务类
 * 提供数据分析、统计和洞察功能
 */
export class ColorAnalytics {
  private static instance: ColorAnalytics;

  private constructor() {}

  public static getInstance(): ColorAnalytics {
    if (!ColorAnalytics.instance) {
      ColorAnalytics.instance = new ColorAnalytics();
    }
    return ColorAnalytics.instance;
  }

  /**
   * 获取用户色彩使用统计
   */
  async getUserColorStats(): Promise<ColorUsageStats> {
    try {
      const schemes = await StorageService.getColorSchemes();
      return this.calculateColorStats(schemes);
    } catch (error) {
      console.error('Failed to get user color stats:', error);
      return this.getDefaultStats();
    }
  }

  /**
   * 分析色彩和谐度
   */
  analyzeColorHarmony(colors: Color[]): number {
    if (colors.length < 2) return 0;

    let totalHarmony = 0;
    let pairCount = 0;

    // 分析每对颜色的和谐度
    for (let i = 0; i < colors.length - 1; i++) {
      for (let j = i + 1; j < colors.length; j++) {
        const harmony = this.calculatePairHarmony(colors[i], colors[j]);
        totalHarmony += harmony;
        pairCount++;
      }
    }

    return pairCount > 0 ? (totalHarmony / pairCount) * 100 : 0;
  }

  /**
   * 分析色彩对比度
   */
  analyzeColorContrast(foreground: Color, background: Color): {
    ratio: number;
    wcagAA: boolean;
    wcagAAA: boolean;
    grade: 'A' | 'B' | 'C' | 'D';
  } {
    const ratio = ColorUtils.getContrast(foreground, background);
    
    return {
      ratio,
      wcagAA: ratio >= 4.5,
      wcagAAA: ratio >= 7,
      grade: ratio >= 7 ? 'A' : ratio >= 4.5 ? 'B' : ratio >= 3 ? 'C' : 'D'
    };
  }

  /**
   * 生成个人洞察
   */
  async generateInsights(): Promise<string[]> {
    const stats = await this.getUserColorStats();
    const insights: string[] = [];

    // 分析最喜欢的颜色
    if (stats.favoriteColors.length > 0) {
      const topColor = stats.favoriteColors[0];
      const temperature = ColorUtils.getTemperature(topColor);
      insights.push(`您最常使用的颜色是 ${topColor.hex}，属于${temperature === 'warm' ? '暖色调' : temperature === 'cool' ? '冷色调' : '中性色调'}`);
    }

    // 分析色彩分布
    const colorDist = stats.colorDistribution;
    const sortedColors = Object.entries(colorDist).sort(([,a], [,b]) => b - a);
    if (sortedColors.length > 0) {
      const [mostUsedRange, count] = sortedColors[0];
      insights.push(`您偏好使用${mostUsedRange}系颜色，占总使用量的 ${((count / stats.totalSchemes) * 100).toFixed(1)}%`);
    }

    // 分析创建频率
    const creationData = Object.values(stats.creationFrequency);
    if (creationData.length > 0) {
      const avgCreation = creationData.reduce((a, b) => a + b, 0) / creationData.length;
      if (avgCreation > 2) {
        insights.push('您是一个活跃的色彩创作者，经常创建新的搭配方案');
      } else if (avgCreation > 1) {
        insights.push('您有规律地创建色彩方案，保持着不错的创作频率');
      }
    }

    // 分析方案类型偏好
    const typeUsage = stats.mostUsedTypes;
    const sortedTypes = Object.entries(typeUsage).sort(([,a], [,b]) => b - a);
    if (sortedTypes.length > 0) {
      const [favoriteType] = sortedTypes[0];
      const typeNames: { [key: string]: string } = {
        'complementary': '互补色',
        'analogous': '类似色',
        'triadic': '三角色',
        'tetradic': '四角色',
        'monochromatic': '单色调',
        'custom': '自定义'
      };
      insights.push(`您偏好创建${typeNames[favoriteType] || favoriteType}类型的搭配方案`);
    }

    // 色彩平衡分析
    const avgColorsPerScheme = stats.averageColorsPerScheme;
    if (avgColorsPerScheme > 5) {
      insights.push('您喜欢创建丰富多彩的调色板，平均每个方案包含较多颜色');
    } else if (avgColorsPerScheme < 3) {
      insights.push('您偏好简洁的色彩搭配，通常使用较少的颜色数量');
    }

    return insights.length > 0 ? insights : ['继续创建更多色彩方案来获得个性化洞察'];
  }

  /**
   * 检测色彩趋势
   */
  async detectColorTrends(): Promise<{
    trendingColors: Color[];
    growingColors: Color[];
    seasonalColors: Color[];
  }> {
    // 模拟趋势数据（实际应用中可以连接真实的趋势API）
    const currentMonth = new Date().getMonth();
    
    const trendingColors = [
      ColorUtils.fromHex('#6366F1'), // Indigo
      ColorUtils.fromHex('#F59E0B'), // Amber
      ColorUtils.fromHex('#10B981'), // Emerald
      ColorUtils.fromHex('#F43F5E'), // Rose
      ColorUtils.fromHex('#8B5CF6')  // Violet
    ];

    const growingColors = [
      ColorUtils.fromHex('#06B6D4'), // Cyan
      ColorUtils.fromHex('#84CC16'), // Lime
      ColorUtils.fromHex('#F97316'), // Orange
    ];

    // 季节性颜色
    const seasonalColors = this.getSeasonalColors(currentMonth);

    return {
      trendingColors,
      growingColors,
      seasonalColors
    };
  }

  /**
   * 生成使用报告
   */
  async generateUsageReport(): Promise<{
    summary: {
      totalSchemes: number;
      totalColors: number;
      averageHarmony: number;
      mostProductiveDay: string;
    };
    trends: {
      weeklyActivity: { week: string; count: number }[];
      colorPreferences: { color: string; percentage: number }[];
      typeDistribution: { type: string; count: number }[];
    };
    recommendations: string[];
  }> {
    const stats = await this.getUserColorStats();
    const schemes = await StorageService.getColorSchemes();
    
    // 计算平均和谐度
    let totalHarmony = 0;
    let harmonyCount = 0;
    
    schemes.forEach(scheme => {
      if (scheme.colors.length > 1) {
        totalHarmony += this.analyzeColorHarmony(scheme.colors);
        harmonyCount++;
      }
    });
    
    const averageHarmony = harmonyCount > 0 ? totalHarmony / harmonyCount : 0;

    // 分析最活跃的日期
    const dateFrequency: { [date: string]: number } = {};
    schemes.forEach(scheme => {
      const date = new Date(scheme.createdAt).toDateString();
      dateFrequency[date] = (dateFrequency[date] || 0) + 1;
    });
    
    const mostProductiveDay = Object.entries(dateFrequency)
      .sort(([,a], [,b]) => b - a)[0]?.[0] || '无数据';

    // 生成建议
    const recommendations = await this.generateRecommendations(stats, averageHarmony);

    return {
      summary: {
        totalSchemes: stats.totalSchemes,
        totalColors: schemes.reduce((sum, s) => sum + s.colors.length, 0),
        averageHarmony,
        mostProductiveDay
      },
      trends: {
        weeklyActivity: this.calculateWeeklyActivity(schemes),
        colorPreferences: this.calculateColorPreferences(stats),
        typeDistribution: Object.entries(stats.mostUsedTypes).map(([type, count]) => ({
          type,
          count
        }))
      },
      recommendations
    };
  }

  // 私有方法

  private calculateColorStats(schemes: ColorScheme[]): ColorUsageStats {
    const colorDistribution: { [hueRange: string]: number } = {};
    const creationFrequency: { [date: string]: number } = {};
    const mostUsedTypes: { [type: string]: number } = {};
    const allColors = schemes.flatMap(s => s.colors);

    // 色相分布统计
    allColors.forEach(color => {
      const hue = color.hsl.h;
      const range = this.getHueRangeName(hue);
      colorDistribution[range] = (colorDistribution[range] || 0) + 1;
    });

    // 创建频率统计
    schemes.forEach(scheme => {
      const date = new Date(scheme.createdAt).toDateString();
      creationFrequency[date] = (creationFrequency[date] || 0) + 1;
    });

    // 类型使用统计
    schemes.forEach(scheme => {
      mostUsedTypes[scheme.type] = (mostUsedTypes[scheme.type] || 0) + 1;
    });

    // 计算最受欢迎的颜色
    const colorFrequency = new Map<string, { color: Color; count: number }>();
    allColors.forEach(color => {
      const hex = color.hex;
      if (colorFrequency.has(hex)) {
        colorFrequency.get(hex)!.count++;
      } else {
        colorFrequency.set(hex, { color, count: 1 });
      }
    });

    const favoriteColors = Array.from(colorFrequency.values())
      .sort((a, b) => b.count - a.count)
      .slice(0, 10)
      .map(item => item.color);

    return {
      totalSchemes: schemes.length,
      favoriteColors,
      colorDistribution,
      averageColorsPerScheme: schemes.length > 0 ? allColors.length / schemes.length : 0,
      creationFrequency,
      mostUsedTypes
    };
  }

  private calculatePairHarmony(color1: Color, color2: Color): number {
    const hsl1 = color1.hsl;
    const hsl2 = color2.hsl;

    // 计算色相差
    const hueDiff = Math.min(Math.abs(hsl1.h - hsl2.h), 360 - Math.abs(hsl1.h - hsl2.h));
    
    // 基于色彩理论的和谐度评分
    let harmonyScore = 0;

    // 互补色关系 (180度)
    if (Math.abs(hueDiff - 180) < 15) {
      harmonyScore = 0.9;
    }
    // 三分关系 (120度)
    else if (Math.abs(hueDiff - 120) < 15 || Math.abs(hueDiff - 240) < 15) {
      harmonyScore = 0.8;
    }
    // 类似色关系 (30度以内)
    else if (hueDiff < 30) {
      harmonyScore = 0.7;
    }
    // 其他关系
    else {
      harmonyScore = 0.3;
    }

    // 饱和度和明度一致性加分
    const satDiff = Math.abs(hsl1.s - hsl2.s);
    const lightDiff = Math.abs(hsl1.l - hsl2.l);
    
    if (satDiff < 20) harmonyScore += 0.1;
    if (lightDiff < 20) harmonyScore += 0.1;

    return Math.min(1, harmonyScore);
  }

  private getHueRangeName(hue: number): string {
    if (hue >= 0 && hue < 30) return '红色';
    if (hue >= 30 && hue < 60) return '橙色';
    if (hue >= 60 && hue < 90) return '黄色';
    if (hue >= 90 && hue < 150) return '绿色';
    if (hue >= 150 && hue < 210) return '青色';
    if (hue >= 210 && hue < 270) return '蓝色';
    if (hue >= 270 && hue < 330) return '紫色';
    return '洋红';
  }

  private getSeasonalColors(month: number): Color[] {
    if (month >= 2 && month <= 4) {
      // 春季
      return [
        ColorUtils.fromHex('#98FB98'), // 淡绿色
        ColorUtils.fromHex('#FFB6C1'), // 淡粉色
        ColorUtils.fromHex('#F0E68C'), // 卡其色
        ColorUtils.fromHex('#87CEEB')  // 天蓝色
      ];
    } else if (month >= 5 && month <= 7) {
      // 夏季
      return [
        ColorUtils.fromHex('#FF6347'), // 番茄红
        ColorUtils.fromHex('#40E0D0'), // 绿松石
        ColorUtils.fromHex('#FFD700'), // 金色
        ColorUtils.fromHex('#32CD32')  // 酸橙绿
      ];
    } else if (month >= 8 && month <= 10) {
      // 秋季
      return [
        ColorUtils.fromHex('#D2691E'), // 巧克力色
        ColorUtils.fromHex('#B22222'), // 火砖色
        ColorUtils.fromHex('#DAA520'), // 金麒麟色
        ColorUtils.fromHex('#8B4513')  // 马鞍棕色
      ];
    } else {
      // 冬季
      return [
        ColorUtils.fromHex('#4169E1'), // 皇家蓝
        ColorUtils.fromHex('#2F4F4F'), // 深石板灰
        ColorUtils.fromHex('#C0C0C0'), // 银色
        ColorUtils.fromHex('#800080')  // 紫色
      ];
    }
  }

  private calculateWeeklyActivity(schemes: ColorScheme[]): { week: string; count: number }[] {
    const weeklyData: { [week: string]: number } = {};
    
    schemes.forEach(scheme => {
      const date = new Date(scheme.createdAt);
      const weekStart = new Date(date.setDate(date.getDate() - date.getDay()));
      const weekKey = weekStart.toISOString().split('T')[0];
      weeklyData[weekKey] = (weeklyData[weekKey] || 0) + 1;
    });

    return Object.entries(weeklyData)
      .map(([week, count]) => ({ week, count }))
      .sort((a, b) => a.week.localeCompare(b.week))
      .slice(-8); // 最近8周
  }

  private calculateColorPreferences(stats: ColorUsageStats): { color: string; percentage: number }[] {
    const total = Object.values(stats.colorDistribution).reduce((sum, count) => sum + count, 0);
    
    return Object.entries(stats.colorDistribution)
      .map(([color, count]) => ({
        color,
        percentage: total > 0 ? (count / total) * 100 : 0
      }))
      .sort((a, b) => b.percentage - a.percentage)
      .slice(0, 5);
  }

  private async generateRecommendations(stats: ColorUsageStats, averageHarmony: number): Promise<string[]> {
    const recommendations: string[] = [];

    if (averageHarmony < 50) {
      recommendations.push('考虑学习更多色彩理论知识，提高色彩搭配的和谐度');
    }

    if (stats.totalSchemes < 5) {
      recommendations.push('多创建一些色彩方案来丰富您的作品集');
    }

    if (stats.averageColorsPerScheme > 7) {
      recommendations.push('尝试创建更简洁的配色方案，有时少即是多');
    }

    const colorTypes = Object.keys(stats.mostUsedTypes);
    if (colorTypes.length < 3) {
      recommendations.push('尝试不同类型的配色方案，如互补色、类似色等');
    }

    if (recommendations.length === 0) {
      recommendations.push('您的色彩运用很出色，继续保持创作热情！');
    }

    return recommendations;
  }

  private getDefaultStats(): ColorUsageStats {
    return {
      totalSchemes: 0,
      favoriteColors: [],
      colorDistribution: {},
      averageColorsPerScheme: 0,
      creationFrequency: {},
      mostUsedTypes: {}
    };
  }
}

// 导出单例实例
export const Analytics = ColorAnalytics.getInstance();